/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: syyyy
 * Date: 2025-08-23
 * Time: 17:49
 */
public class MyPriorityQueue {
    public int[] elem;
    public int usedSize;

    public MyPriorityQueue() {
        elem = new int[10];
    }

    public void iniElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];//这一步是为了能够让elem数组有更多种可能
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);//parent从最后一棵子树开始
        }
    }

    private void siftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {//不包括usedSize
            if (child + 1 < usedSize && this.elem[child] < this.elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;//如果没有交换                
            }
        }
    }

    public void offer(int val) {
        if (isFull()) {
            return;
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    private void siftUp(int child) {//这个child也指的是从哪里开始调整
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int poll() {
        if (isEmpty()) {
            return -1;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = tmp;

        int val = elem[0];
        usedSize--;
        siftDown(0, usedSize);

        return val;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return elem[0];
    }


    public void headSort() {
        int end = usedSize - 1;
        while(end > 0){
            int tmp=elem[0];
            elem[0]=elem[end];
            elem[end]=tmp;
            siftDown(0,end);//不包括end
            end--;
        }
    }

}
